<template>
  <!-- a-modal -->
  <a-modal
    v-if="modal"
    :open="visible"
    :footer="null"
    :destroy-on-close="true"
    width="fit-content"
    class="min-w-100"
    @update:open="$emit('update:visible', $event)"
  >
    <template #title>
      <a-input
        :value="modal?.title"
        class="max-w-20"
        @update:value="$emit('update:modal', { ...modal, title: $event })"
      ></a-input>
    </template>
    <a-form>
      <a-row flex justify="center" class="m-5">
        <a-col :span="24" class="space-y-3">
          <component
            :is="`Edit${capitalize(comp.type)}`"
            v-for="(comp, index) in formItems"
            :key="comp.id"
            :item="comp"
            class="mb-0!"
            @update:item="Object.assign(comp, $event)"
            @remove="removeItem(index)"
          ></component>
          <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
            <a-dropdown :trigger="['hover', 'click']">
              <a-button type="dashed" style="width: 100%" @click="() => false">
                <PlusOutlined />
                添加
              </a-button>
              <template #overlay>
                <a-menu @click="addItem">
                  <a-menu-item v-for="itemType in Object.keys(createMap)" :key="itemType">{{
                    createMap[itemType]
                  }}</a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts" name="editable-moda">
import { PlusOutlined } from '@ant-design/icons-vue'
import type { MenuClickEventHandler } from 'ant-design-vue/es/menu/src/interface'
import { keyModal } from '../key'
import { capitalize } from '@/utils/tool'
import { createMap, createFormItemUtils } from '@/utils/create'
import { Modal } from '@/form'

const { formItems } = inject(keyModal)!

defineProps<{
  visible: boolean
  modal?: Modal
}>()

defineEmits<{
  (event: 'update:visible', visible: boolean)
  (event: 'update:modal', value: Modal)
}>()

const addItem: MenuClickEventHandler = ({ key }) => {
  formItems.value.push(createFormItemUtils[`create${capitalize(key as string)}`]())
}

const removeItem = (index: number) => {
  formItems.value.splice(index, 1)
}
</script>

<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 0;
}
</style>
